import logging
from typing import Dict, List, Any, Optional, Type
from .base_processor import BaseProcessor
from .summary_processor import SummaryProcessor
from .classification_processor import ClassificationProcessor

class ProcessorManager:
    """
    处理器管理器，负责协调数据处理流程
    """
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化处理器管理器
        
        Args:
            config: 配置数据
        """
        self.logger = logging.getLogger("processor.manager")
        self.config = config
        
        # 初始化处理器
        self.processors = {}
        self._init_processors()
    
    def _init_processors(self) -> None:
        """
        初始化所有处理器
        """
        try:
            # 摘要处理器
            self.processors['summary'] = SummaryProcessor(self.config)
            self.logger.info("Initialized summary processor")
            
            # 分类处理器
            self.processors['classification'] = ClassificationProcessor(self.config)
            self.logger.info("Initialized classification processor")
            
            # 可以添加更多处理器
            
        except Exception as e:
            self.logger.error(f"Failed to initialize processors: {str(e)}")
    
    def get_processor(self, processor_name: str) -> Optional[BaseProcessor]:
        """
        获取指定处理器
        
        Args:
            processor_name: 处理器名称
            
        Returns:
            处理器实例
        """
        return self.processors.get(processor_name)
    
    def process_data(self, data: List[Dict[str, Any]], processors: Optional[List[str]] = None) -> List[Dict[str, Any]]:
        """
        使用指定的处理器处理数据
        
        Args:
            data: 要处理的数据
            processors: 要使用的处理器名称列表，为None则使用所有处理器
            
        Returns:
            处理后的数据
        """
        if not data:
            self.logger.warning("No data to process")
            return []
            
        # 如果未指定处理器，使用默认顺序
        if not processors:
            processors = ['summary', 'classification']
            
        processed_data = data
        for processor_name in processors:
            processor = self.get_processor(processor_name)
            if not processor:
                self.logger.warning(f"Processor {processor_name} not found, skipping")
                continue
                
            try:
                self.logger.info(f"Processing data with {processor_name} processor")
                processed_data = processor.process(processed_data)
                self.logger.info(f"Completed processing with {processor_name} processor")
            except Exception as e:
                self.logger.error(f"Error processing data with {processor_name} processor: {str(e)}")
                
        return processed_data
        
    def process_data_by_type(self, data: Dict[str, List[Dict[str, Any]]], processors: Optional[List[str]] = None) -> Dict[str, List[Dict[str, Any]]]:
        """
        按类型处理数据
        
        Args:
            data: 按类型分组的数据字典
            processors: 要使用的处理器名称列表，为None则使用所有处理器
            
        Returns:
            处理后的数据字典
        """
        result = {}
        
        for key, items in data.items():
            self.logger.info(f"Processing data for {key}")
            result[key] = self.process_data(items, processors)
            
        return result 